 package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.Caja;
import ar.republicagroup.gestion.entities.CalendarioBancario;
import ar.republicagroup.gestion.entities.CierreCaja;
import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.entities.Usuario;
import ar.republicagroup.gestion.services.CajaServices;
import ar.republicagroup.gestion.services.CalendarioBancarioServices;
import ar.republicagroup.gestion.services.CierreCajaServices;
import ar.republicagroup.gestion.services.ClienteServices;
import ar.republicagroup.gestion.services.MovimientoTipoServices;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.UserSession;
import ar.republicagroup.gestion.util.exportar.Exportar;
import ar.republicagroup.gestion.util.helpers.FilterCaja;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.helpers.UserInterfaceHelper;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static ch.lambdaj.Lambda.*;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

public class FrmCajaDiaria extends javax.swing.JFrame {

    
    private static FrmCajaDiaria instance;
    private List<Caja> movimientosCaja;
    private List<Caja> retirosCaja = new ArrayList();
    private List<Caja> pagosCaja = new ArrayList();
    private List<Caja> gastosDiariosCaja = new ArrayList();
    private List<Caja> gastosBanco = new ArrayList();
    Set<CalendarioBancario> calendarioSet = new HashSet<>();
    private Calendar fechaSeleccionada;
    
    /* Services */
    CajaServices cajaServices = (CajaServices)SpringUtils.getBean("cajaServices");
    
    private double totalCajaAnterior;
    private Task task;
    private String absolutePathExportXls; 
    private static Logger log               =  Logger.getLogger(FrmCajaDiaria.class);
    
        
    private FrmCajaDiaria() {
        initComponents();
        valoresPorDefecto();
    }

    public static FrmCajaDiaria getInstance(){
        if(instance == null){
            instance = new FrmCajaDiaria();
        }
        return instance;
    }
    
    
    private void valoresPorDefecto(){
        
        UserInterfaceHelper.setJFrameIconImage(this);
        UserInterfaceHelper.setTitleToThisJFrame(this, "...: Caja Diaria :..");
        calendarFechaCaja.setDate(new Date());
        String currentDate = Formato.cambiarFechaAFormatoLocal(new Date());
        lblFechaCaja.setText(currentDate);
        txtTotalGastosBancos.setText(Formato.decimalComaMilesConSigno(0));
        txtTotalGastosDiarios.setText(Formato.decimalComaMilesConSigno(0));
        txtTotalPagos.setText(Formato.decimalComaMilesConSigno(0));
        txtTotalRetiros.setText(Formato.decimalComaMilesConSigno(0));
        /* Sincronizamos el calendario con el calendario bancario */
        Locale local = new Locale("es", "US");
        calendarFechaCaja.setLocale(local);
        CalendarioBancarioServices calendarioBancarioServices = (CalendarioBancarioServices)SpringUtils.getBean("calendarioBancarioServices");
        calendarioSet = calendarioBancarioServices.findEntities();
        
        
        Date today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        
        
        boolean todayIsHoliday = calendarioBancarioServices.isHoliday(today, calendarioSet);
        
        
        if(todayIsHoliday){
            btnNuevoMov.setEnabled(false);
            btnCerrarCaja.setEnabled(false);
        }
        
        UserInterfaceHelper.drawHolidaysOnThisCalendar(calendarFechaCaja, calendarioSet);
        actualizarMovimientos();
        
 
    }
 
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPopupMenu1 = new javax.swing.JPopupMenu();
        menuItemDelete1 = new javax.swing.JMenuItem();
        jPopupMenu2 = new javax.swing.JPopupMenu();
        menuItemDelete2 = new javax.swing.JMenuItem();
        jPopupMenu3 = new javax.swing.JPopupMenu();
        menuItemDelete3 = new javax.swing.JMenuItem();
        jPopupMenu4 = new javax.swing.JPopupMenu();
        menuItemDelete4 = new javax.swing.JMenuItem();
        jFileChooser1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblRetiros = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        txtTotalRetiros = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblPagos = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        txtTotalPagos = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblGastosDiarios = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        txtTotalGastosDiarios = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        tblGastosBancos = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();
        txtTotalGastosBancos = new javax.swing.JTextField();
        jPanel6 = new javax.swing.JPanel();
        btnNuevoMov = new javax.swing.JButton();
        btnExportarExcel = new javax.swing.JButton();
        btnCerrarCaja = new javax.swing.JButton();
        btnActualizar = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        lblEfectivoCajaAnt = new javax.swing.JLabel();
        lblTotalEfectivoCaja = new javax.swing.JLabel();
        calendarFechaCaja = new com.toedter.calendar.JCalendar();
        jPanel8 = new javax.swing.JPanel();
        lblFechaCaja = new javax.swing.JLabel();
        btnCambiar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        lblEstadoCierre = new javax.swing.JLabel();
        btnSaldoClientes = new javax.swing.JButton();

        menuItemDelete1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/delete.png"))); // NOI18N
        menuItemDelete1.setText("Eliminar");
        menuItemDelete1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemDelete1ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(menuItemDelete1);

        menuItemDelete2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/delete.png"))); // NOI18N
        menuItemDelete2.setText("Eliminar");
        menuItemDelete2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemDelete2ActionPerformed(evt);
            }
        });
        jPopupMenu2.add(menuItemDelete2);

        menuItemDelete3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/delete.png"))); // NOI18N
        menuItemDelete3.setText("Eliminar");
        menuItemDelete3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemDelete3ActionPerformed(evt);
            }
        });
        jPopupMenu3.add(menuItemDelete3);

        menuItemDelete4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/delete.png"))); // NOI18N
        menuItemDelete4.setText("Eliminar");
        menuItemDelete4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemDelete4ActionPerformed(evt);
            }
        });
        jPopupMenu4.add(menuItemDelete4);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Retiros"));

        tblRetiros.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Banco", "Importe"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblRetiros.setComponentPopupMenu(jPopupMenu1);
        jScrollPane1.setViewportView(tblRetiros);

        jLabel2.setText("Total retiros");

        txtTotalRetiros.setEditable(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtTotalRetiros)))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtTotalRetiros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Pagos"));

        tblPagos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cliente", "Importe"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblPagos.setComponentPopupMenu(jPopupMenu2);
        jScrollPane2.setViewportView(tblPagos);

        jLabel3.setText("Total pagos");

        txtTotalPagos.setEditable(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtTotalPagos)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtTotalPagos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Gastos diarios"));

        tblGastosDiarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Concepto", "Importe"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblGastosDiarios.setComponentPopupMenu(jPopupMenu3);
        jScrollPane3.setViewportView(tblGastosDiarios);

        jLabel4.setText("Total gastos");

        txtTotalGastosDiarios.setEditable(false);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTotalGastosDiarios)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtTotalGastosDiarios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Gastos bancos"));
        jPanel5.setPreferredSize(new java.awt.Dimension(292, 394));

        tblGastosBancos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Concepto", "Importe"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblGastosBancos.setComponentPopupMenu(jPopupMenu4);
        jScrollPane4.setViewportView(tblGastosBancos);

        jLabel5.setText("Gastos bancos");

        txtTotalGastosBancos.setEditable(false);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtTotalGastosBancos)))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtTotalGastosBancos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Operaciones"));

        btnNuevoMov.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cash_register_16x16.png"))); // NOI18N
        btnNuevoMov.setText("Movimiento");
        btnNuevoMov.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoMovActionPerformed(evt);
            }
        });

        btnExportarExcel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/excel_16_16.png"))); // NOI18N
        btnExportarExcel.setText("Exportar");
        btnExportarExcel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportarExcelActionPerformed(evt);
            }
        });

        btnCerrarCaja.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/lock_16_16.png"))); // NOI18N
        btnCerrarCaja.setText("Cerrar caja");
        btnCerrarCaja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarCajaActionPerformed(evt);
            }
        });

        btnActualizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/update.png"))); // NOI18N
        btnActualizar.setText("Actualizar");
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(btnNuevoMov)
                .addGap(18, 18, 18)
                .addComponent(btnExportarExcel)
                .addGap(18, 18, 18)
                .addComponent(btnCerrarCaja)
                .addGap(18, 18, 18)
                .addComponent(btnActualizar)
                .addContainerGap(31, Short.MAX_VALUE))
        );

        jPanel6Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnActualizar, btnCerrarCaja, btnExportarExcel, btnNuevoMov});

        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNuevoMov)
                    .addComponent(btnExportarExcel)
                    .addComponent(btnCerrarCaja)
                    .addComponent(btnActualizar))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Efectivo caja anterior: ");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Total efectivo caja:");

        lblEfectivoCajaAnt.setText("$0");

        lblTotalEfectivoCaja.setText("$0");

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addGap(18, 18, 18)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblTotalEfectivoCaja)
                    .addComponent(lblEfectivoCajaAnt))
                .addContainerGap(113, Short.MAX_VALUE))
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(lblEfectivoCajaAnt))
                .addGap(18, 18, 18)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(lblTotalEfectivoCaja))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        calendarFechaCaja.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                calendarFechaCajaPropertyChange(evt);
            }
        });

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Caja del día"));

        lblFechaCaja.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblFechaCaja.setText("fecha");

        btnCambiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/calendar.png"))); // NOI18N
        btnCambiar.setText("Cambiar fecha");
        btnCambiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCambiarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Estado cierre: ");

        lblEstadoCierre.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblEstadoCierre.setText("-");

        btnSaldoClientes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cash_register.png"))); // NOI18N
        btnSaldoClientes.setText("Saldo clientes");
        btnSaldoClientes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaldoClientesActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblFechaCaja, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel8Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblEstadoCierre))
                    .addGroup(jPanel8Layout.createSequentialGroup()
                        .addComponent(btnCambiar, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnSaldoClientes)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel8Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCambiar, btnSaldoClientes});

        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblFechaCaja)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lblEstadoCierre))
                .addGap(18, 18, 18)
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCambiar)
                    .addComponent(btnSaldoClientes))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(calendarFechaCaja, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(calendarFechaCaja, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 406, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 10, 11, 0);
        getContentPane().add(jPanel1, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNuevoMovActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoMovActionPerformed
        
            CierreCajaServices caja = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
            Calendar today = Calendar.getInstance();
            
            if(! caja.isCierreCajaClosed(today) ){
            
                FrmAddMovimientoCaja panel = new FrmAddMovimientoCaja(this, true);
                UserInterfaceHelper.centreWindow(panel);
                panel.setVisible(true);

                if( panel.isMovimientosRegistered() ){
                    actualizarMovimientos();
                }
            
            }else{
                JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("closedCaja"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
                btnNuevoMov.setEnabled(false);
                btnCerrarCaja.setEnabled(false);
            }
        
    }//GEN-LAST:event_btnNuevoMovActionPerformed
    
    private void actualizarMovimientos(){
        
        fechaSeleccionada = calendarFechaCaja.getCalendar();
        
        if( fechaSeleccionada.before(Calendar.getInstance()) ){
        
            getCajaAnterior(fechaSeleccionada);

            String currentDate = Formato.cambiarFechaAFormatoLocal(fechaSeleccionada.getTime());
            lblFechaCaja.setText(currentDate);
            movimientosCaja     = cajaServices.getMovimientosCajaByFecha(fechaSeleccionada);
            retirosCaja         = select(movimientosCaja,FilterCaja.filterCajaByTipoMovimiento(MovimientoTipoServices.RETIRO_ID));
            pagosCaja           = select(movimientosCaja,FilterCaja.filterCajaByTipoMovimiento(MovimientoTipoServices.PAGOS_ID));
            gastosDiariosCaja   = select(movimientosCaja,FilterCaja.filterCajaByTipoMovimiento(MovimientoTipoServices.GASTOS_DIARIO_ID));
            gastosBanco         = select(movimientosCaja,FilterCaja.filterCajaByTipoMovimiento(MovimientoTipoServices.GASTOS_BANCO_ID));
            cargarTablaRetiros(retirosCaja);
            cargarTablaPagos(pagosCaja);
            cargarTablaGastosDiarios(gastosDiariosCaja);
            cargarTablaGastosBanco(gastosBanco);

            double totalEfectivoCajaDelDia = cajaServices.getTotalEfectivoEnCajaDelDia();
            lblTotalEfectivoCaja.setText(Formato.decimalComaMilesConSigno(totalEfectivoCajaDelDia));
            
            /* Revisamos si la caja está cerrada o no */
            CierreCajaServices caja = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
            
            if( caja.isCierreCajaClosed(fechaSeleccionada) ){
                lblEstadoCierre.setText(CierreCajaServices.CAJA_CERRADA);
                btnNuevoMov.setEnabled(Boolean.FALSE);
                btnCerrarCaja.setEnabled(Boolean.FALSE);
            } else {
                lblEstadoCierre.setText(CierreCajaServices.CAJA_ABIERTA);
                btnNuevoMov.setEnabled(Boolean.TRUE);
                btnCerrarCaja.setEnabled(Boolean.TRUE);
            }
            
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("futureDateSelected"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    private void getCajaAnterior(Calendar fechaElegida){
    
        /* Obtenemos los datos de la caja anterior */
        CalendarioBancarioServices calendarioBancarioServices = (CalendarioBancarioServices)SpringUtils.getBean("calendarioBancarioServices");
        Calendar fechaCajaAnterior = calendarioBancarioServices.calcularAnteriorDiaHabil(fechaElegida);
        CierreCajaServices cierreCajaServices = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
        CierreCaja cajaAnterior = cierreCajaServices.getCierreCajaByFecha(fechaCajaAnterior);
        
        if(cajaAnterior != null){
            totalCajaAnterior   = cajaAnterior.getEfectivoCaja();
        } else {
            totalCajaAnterior   = 0;
        }
        
        lblEfectivoCajaAnt.setText(Formato.decimalComaMilesConSigno(totalCajaAnterior));
        cajaServices.setEfectivoCajaAnterior(totalCajaAnterior);
    }
    
    
    public void cargarTablaRetiros(List<Caja> retirosCaja){
        
        double totalRetiros = 0;
        
        DefaultTableModel model = (DefaultTableModel)tblRetiros.getModel();
        model.getDataVector().clear();
        
        for(Caja retiro : retirosCaja){
            model.addRow(new Object[]{ retiro.getCuentaBancoId().getNombre(), retiro });
            totalRetiros += retiro.getImporte().doubleValue();
        }
        
        tblRetiros.setModel(model);
        tblRetiros.repaint();
        tblRetiros.getSelectionModel().clearSelection();
        
        txtTotalRetiros.setText(Formato.decimalComaMilesConSigno(totalRetiros));
        cajaServices.setTotalRetiros(totalRetiros);
    
    }
    
    public void cargarTablaPagos(List<Caja> pagosCaja){
        
        double totalPagos = 0;
        
        DefaultTableModel model = (DefaultTableModel)tblPagos.getModel();
        model.getDataVector().clear();
        
        for(Caja pago : pagosCaja){
            model.addRow(new Object[]{ pago.getClienteId().getNombre() , pago  });
            totalPagos += pago.getImporte().doubleValue();
        }
        
        tblPagos.setModel(model);
        tblPagos.repaint();
        tblPagos.getSelectionModel().clearSelection();
        
        txtTotalPagos.setText(Formato.decimalComaMilesConSigno(totalPagos));
        cajaServices.setTotalPagos(totalPagos);
    }
    
    public void cargarTablaGastosDiarios(List<Caja> gastosDiariosList){
    
        double totalGastosDiarios = 0;
        
        DefaultTableModel model = (DefaultTableModel)tblGastosDiarios.getModel();
        model.getDataVector().clear();
        
        for(Caja gastoDiario : gastosDiariosList){
            model.addRow(new Object[]{ gastoDiario.getDescripcion(), gastoDiario });
            totalGastosDiarios += gastoDiario.getImporte().doubleValue();
        }
        
        tblGastosDiarios.setModel(model);
        tblGastosDiarios.repaint();
        tblGastosDiarios.getSelectionModel().clearSelection();
        
        txtTotalGastosDiarios.setText(Formato.decimalComaMilesConSigno(totalGastosDiarios));
        cajaServices.setTotalGastosDiarios(totalGastosDiarios);
    }
    
    public void cargarTablaGastosBanco(List<Caja> gastosBancoList){
        
        double totalGastosBanco = 0;
        
        DefaultTableModel model = (DefaultTableModel)tblGastosBancos.getModel();
        model.getDataVector().clear();
        
        for(Caja gastoBanco : gastosBancoList){
            model.addRow(new Object[]{ gastoBanco.getDescripcion(), gastoBanco });
            totalGastosBanco += gastoBanco.getImporte().doubleValue();
        }
        
        tblGastosBancos.setModel(model);
        tblGastosBancos.repaint();
        tblGastosBancos.getSelectionModel().clearSelection();
        
        txtTotalGastosBancos.setText(Formato.decimalComaMilesConSigno(totalGastosBanco));
        cajaServices.setTotalGastosBancos(totalGastosBanco);
    }
    
    
    private void btnCambiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCambiarActionPerformed
        actualizarMovimientos();
    }//GEN-LAST:event_btnCambiarActionPerformed

    private void menuItemDelete1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemDelete1ActionPerformed
        
       CierreCajaServices caja = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
       
       if(! caja.isCierreCajaClosed( fechaSeleccionada ) ){
           if( UserSession.getInstance().getPerfil_id() ==  UserSession.ADMINISTRADOR){
                eliminarMovimientos(retirosCaja, tblRetiros);
                actualizarMovimientos();
                
           } else {
             JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("adminLevelRequired"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);  
           }
       } else {
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("closedCaja"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
       }
       
       
    }//GEN-LAST:event_menuItemDelete1ActionPerformed

    
    private void menuItemDelete2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemDelete2ActionPerformed
        
       CierreCajaServices caja = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
       
       if(! caja.isCierreCajaClosed( fechaSeleccionada ) ){
           if( UserSession.getInstance().getPerfil_id() ==  UserSession.ADMINISTRADOR){
                eliminarMovimientos(pagosCaja, tblPagos);
                actualizarMovimientos();
                
           } else {
               JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("adminLevelRequired"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);  
           }
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("closedCaja"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
        }
       
    }//GEN-LAST:event_menuItemDelete2ActionPerformed

    private void menuItemDelete3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemDelete3ActionPerformed
        
        CierreCajaServices caja = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
        
        if(! caja.isCierreCajaClosed( fechaSeleccionada ) ){
            if( UserSession.getInstance().getPerfil_id() ==  UserSession.ADMINISTRADOR ){
                eliminarMovimientos(gastosDiariosCaja, tblGastosDiarios);
                actualizarMovimientos();
                
            } else {
                JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("adminLevelRequired"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);  
            }
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("closedCaja"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_menuItemDelete3ActionPerformed

    private void menuItemDelete4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemDelete4ActionPerformed
        
        CierreCajaServices caja = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
        
        if(! caja.isCierreCajaClosed( fechaSeleccionada ) ){
            if( UserSession.getInstance().getPerfil_id() ==  UserSession.ADMINISTRADOR ){
                eliminarMovimientos(gastosBanco, tblGastosBancos);
                actualizarMovimientos();
                
            } else {
                JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("adminLevelRequired"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);  
            }
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("closedCaja"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_menuItemDelete4ActionPerformed

    private void btnCerrarCajaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarCajaActionPerformed
        
        CierreCajaServices caja = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
        Calendar today = Calendar.getInstance();
        boolean isCajaClosed = caja.isCierreCajaClosed(today);
        
        if( ! isCajaClosed ){
            if(! movimientosCaja.isEmpty() ){
              if( cajaServices.getTotalEfectivoEnCajaDelDia() > 0 ){  
                int respuesta = JOptionPane.showConfirmDialog(this, UIMessages.getQuestionMessage("confirmCierreCaja"), UIMessages.getQuestionMessage("defaultQuestionTitle"), JOptionPane.YES_NO_OPTION);

                if(respuesta == JOptionPane.YES_OPTION){
                    movimientosCaja = cajaServices.getMovimientosCajaByFecha( fechaSeleccionada );

                    CierreCaja cierreCaja = new CierreCaja();
                    cierreCaja.setFechaCaja(fechaSeleccionada.getTime());
                    cierreCaja.setEfectivoCaja(cajaServices.getTotalEfectivoEnCajaDelDia());
                    cierreCaja.setEfectivoCajaAnterior(cajaServices.getTotalEfectivoCajaAnterior());
                    cierreCaja.setFechaCierre(new Date());
                    cierreCaja.setEstado(Short.valueOf("1"));
                    cierreCaja.setCajaList(movimientosCaja);
                    cierreCaja.setUsuarioId(new Usuario(UserSession.getInstance().getUser_id()));

                    CierreCajaServices cierreCajaServices = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
                    String msjInsert = cierreCajaServices.insert(cierreCaja);

                    if(msjInsert != null){
                        /* Actualizamos cada movimiento , seteandole el id del cierre de caja recién insertado */
                        CierreCaja cierreDelDia = cierreCajaServices.getCierreCajaByFecha(fechaSeleccionada);
                        cajaServices.registrarMovimientosWithCierreCaja(movimientosCaja, cierreDelDia);
                        JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("onCompleteCierreCaja"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
                        btnNuevoMov.setEnabled(false);
                        btnCerrarCaja.setEnabled(false);
                        lblEstadoCierre.setText(CierreCajaServices.CAJA_CERRADA);
                    } else {
                        JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onInsertError"),UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                    }

                    }
                
              } else {
                  JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("totalEfectivoPositivo"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
              }
              
            } else {
                JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("movimientosEmpty"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            }
            
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("closedCaja"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            btnNuevoMov.setEnabled(false);
            btnCerrarCaja.setEnabled(false);
        }
        
        
            
    }//GEN-LAST:event_btnCerrarCajaActionPerformed

    private void btnExportarExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarExcelActionPerformed
       
        if(! movimientosCaja.isEmpty() ){
            
            SimpleDateFormat spanishFormat = new SimpleDateFormat("dd-MM-yyyy");
            String fechaHoy = spanishFormat.format(new Date());
            jFileChooser1.setDialogType(JFileChooser.SAVE_DIALOG);
            jFileChooser1.setAcceptAllFileFilterUsed(true);
            jFileChooser1.setSelectedFile(new File(fechaHoy+"_cajaDiaria.xls"));
            jFileChooser1.setFileSelectionMode(JFileChooser.FILES_ONLY);
            jFileChooser1.setFileFilter(new FileFilter() {
                @Override
				public boolean accept(File file) {
					String fileName = file.getName().toUpperCase();
					if (fileName.endsWith("*.xls")) {
						return true;
					}
                                        
                                        if(file.isDirectory()){
                                            return true;
                                        }
                                        
					return false;
				}
	
				public String getDescription() {
					return "Excel Document (*.xls)";
				}
			});
            
            
            int respuesta = jFileChooser1.showSaveDialog(this);
            
            while (respuesta == JFileChooser.APPROVE_OPTION
                && !jFileChooser1.getSelectedFile().getName().endsWith(".xls")) {
                JOptionPane.showMessageDialog(this, "La extensión del archivo "
                  + jFileChooser1.getSelectedFile().getName() + " debe finalizar en .xls",
                  "Open Error", JOptionPane.ERROR_MESSAGE);
                    respuesta = jFileChooser1.showSaveDialog(this);
                }
            
            if (respuesta == JFileChooser.APPROVE_OPTION ){
                absolutePathExportXls = jFileChooser1.getSelectedFile().getAbsolutePath();
                log.info("Exportando caja diaria en la ruta : "+absolutePathExportXls);
                mostrarBarraDeProgresoEIniciarTask();
            }
            
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("movimientosEmpty"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
        }
        
    }//GEN-LAST:event_btnExportarExcelActionPerformed

    private void calendarFechaCajaPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_calendarFechaCajaPropertyChange
       
        if ("calendar".equals(evt.getPropertyName())) {
            fechaSeleccionada = (Calendar)evt.getNewValue();
            UserInterfaceHelper.drawHolidaysOnThisCalendar(calendarFechaCaja, calendarioSet);
        }
        
        
    }//GEN-LAST:event_calendarFechaCajaPropertyChange

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        absolutePathExportXls = null;
        
        CierreCajaServices caja = (CierreCajaServices)SpringUtils.getBean("cierreCajaServices");
        Calendar today = Calendar.getInstance();
        
        if ( caja.isCierreCajaClosed(today) ){
            lblEstadoCierre.setText(CierreCajaServices.CAJA_CERRADA);
            btnCerrarCaja.setEnabled(Boolean.FALSE);
            btnNuevoMov.setEnabled(Boolean.FALSE);
        }else {
            lblEstadoCierre.setText(CierreCajaServices.CAJA_ABIERTA);
        }
        
        
    }//GEN-LAST:event_formWindowOpened

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
        actualizarMovimientos();
    }//GEN-LAST:event_btnActualizarActionPerformed

    private void btnSaldoClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaldoClientesActionPerformed
        FrmSaldoCliente formulario = new FrmSaldoCliente(this,true);
        UserInterfaceHelper.centreWindow(formulario);
        formulario.setVisible(true);
    }//GEN-LAST:event_btnSaldoClientesActionPerformed

    private void eliminarMovimientos(List<Caja> movimientos,JTable selectedTable){
    
        int[] selectedRows = selectedTable.getSelectedRows();
        List<Caja> objectsToDelete = new ArrayList<>();
        
        for (int i = 0; i < selectedRows.length; i++) {
            
            Caja retiro = (Caja)selectedTable.getValueAt(selectedRows[i], 1);
            objectsToDelete.add(retiro);
        }
        
        CajaServices services = (CajaServices)SpringUtils.getBean("cajaServices");
        
        for( Caja movimiento : objectsToDelete){
            movimiento.setEstado(0);
            movimiento.setUsuarioId(new Usuario(UserSession.getInstance().getUser_id()));
            services.update(movimiento);
        }
 
    
    }
    
    
    public void mostrarBarraDeProgresoEIniciarTask(){
            final BarraDeProgreso barra;
            barra = new BarraDeProgreso(this, false);
            barra.setLocationRelativeTo(this);
            barra.setVisible(true);
            task = new Task();
            task.addPropertyChangeListener(new PropertyChangeListener() {

             @Override
             public void propertyChange(PropertyChangeEvent pcEvt) {
                if (SwingWorker.StateValue.DONE == pcEvt.getNewValue()) {
                   Toolkit.getDefaultToolkit().beep(); 
                   barra.setVisible(false);
                   barra.dispose();            
                }
             }
          });
       
            task.execute();
            
    }
    
    
     /* CLASE INNER */    
    class Task extends SwingWorker<Void, Boolean> {
        
        @Override
        public Void doInBackground() throws Exception {
            Map<String,Object> mapCierreDeCaja = new HashMap<>();
            mapCierreDeCaja.put("retiros", retirosCaja);
            mapCierreDeCaja.put("pagos", pagosCaja);
            mapCierreDeCaja.put("gastosDiarios", gastosDiariosCaja);
            mapCierreDeCaja.put("gastosBanco", gastosBanco);
            mapCierreDeCaja.put("totalEfecCajaDia",cajaServices.getTotalEfectivoEnCajaDelDia());
            mapCierreDeCaja.put("totalEfecCajaAnt",cajaServices.getTotalEfectivoCajaAnterior());
            mapCierreDeCaja.put("totalRetiros",cajaServices.getTotalRetiros());
            mapCierreDeCaja.put("totalPagos",cajaServices.getTotalPagos());
            mapCierreDeCaja.put("totalGastosDiarios", cajaServices.getTotalGastosDiarios());
            mapCierreDeCaja.put("totalGastosBancos", cajaServices.getTotalGastosBancos());
            mapCierreDeCaja.put("absolutePathXLS", absolutePathExportXls);
            boolean exportSuccess = Exportar.cajaDiariaToXLS(mapCierreDeCaja);
            
            if(exportSuccess){
                JOptionPane.showMessageDialog(null, UIMessages.getInfoMessage("exportCajaDiariaOk"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(null, UIMessages.getErrorMessage("onExportError"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            }
            
            return null;
        }
    }
    
    
    
    
    
    
   
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmCajaDiaria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmCajaDiaria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmCajaDiaria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmCajaDiaria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmCajaDiaria().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnCambiar;
    private javax.swing.JButton btnCerrarCaja;
    private javax.swing.JButton btnExportarExcel;
    private javax.swing.JButton btnNuevoMov;
    private javax.swing.JButton btnSaldoClientes;
    private com.toedter.calendar.JCalendar calendarFechaCaja;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JPopupMenu jPopupMenu2;
    private javax.swing.JPopupMenu jPopupMenu3;
    private javax.swing.JPopupMenu jPopupMenu4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JLabel lblEfectivoCajaAnt;
    private javax.swing.JLabel lblEstadoCierre;
    private javax.swing.JLabel lblFechaCaja;
    private javax.swing.JLabel lblTotalEfectivoCaja;
    private javax.swing.JMenuItem menuItemDelete1;
    private javax.swing.JMenuItem menuItemDelete2;
    private javax.swing.JMenuItem menuItemDelete3;
    private javax.swing.JMenuItem menuItemDelete4;
    private javax.swing.JTable tblGastosBancos;
    private javax.swing.JTable tblGastosDiarios;
    private javax.swing.JTable tblPagos;
    private javax.swing.JTable tblRetiros;
    private javax.swing.JTextField txtTotalGastosBancos;
    private javax.swing.JTextField txtTotalGastosDiarios;
    private javax.swing.JTextField txtTotalPagos;
    private javax.swing.JTextField txtTotalRetiros;
    // End of variables declaration//GEN-END:variables
}
